<template>
    <Card>
        <p slot="title">用例列表</p>
        <div slot="extra">
            <Button type="primary" style="margin-right:8px;" @click="handleSelect">查询</Button>
            <Button style="margin-right:8px;" @click="handleReset">重置</Button>
        </div>
        <div style="margin-bottom: -28px">
            <Form ref="FormInline" :model="selectForm" inline :label-width="80" @submit.native.prevent>
                <FormItem label="用例名称">
                    <Input v-model="selectForm.name" placeholder="请输入" @keyup.enter.native="handleSelect"/>
                </FormItem>
                <FormItem label="所属模块">
                    <Select v-model="selectForm.env_id" style="width: 240px">
                        <Option v-for="item in moduleList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="请求接口">
                    <Select v-model="selectForm.interface_id" style="width: 240px">
                        <Option v-for="item in interfaceList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="创建人员">
                    <Select v-model="selectForm.created_by" style="width: 240px">
                        <Option v-for="item in userList" :value="item.user_id" :key="item.user_id">{{
                            item.user_name
                            }}
                        </Option>
                    </Select>
                </FormItem>
            </Form>

        </div>
        <Divider/>
        <div style="margin-top: -16px;margin-bottom: 8px">
            <Button style="margin-right:8px;" type="primary" @click="handleAdd">创建用例</Button>
            <Upload
                    style="display: inline-block; margin-right:8px;"
                    ref="upload"
                    :action="actionUrl"
                    :headers="headers"
                    name="file"
                    :show-upload-list="false"
                    :on-format-error="handleFormatError"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :format="['xlsx','xls']">
                <Button type="primary">导入用例</Button>
            </Upload>
            <Button style="margin-right:8px;" @click="handleTemplate">下载模板</Button>
            <Button style="margin-right:8px;" type="primary" @click="handleExport">导出用例</Button>
            <Button style="margin-right:8px;" type="primary" :disabled="selectData.length < 1"
                    @click="handleBatchExecution">
                批量执行
            </Button>
        </div>
        <div>
            <Table ref="selection" :columns="columns" :data="data" @on-selection-change="handleClick" border
                   style="height: 92%">
                <template slot-scope="{ row, index }" slot="action">
                    <Button type="primary" size="small" style="margin-right: 5px" @click="handleEdit(row.id)">编辑
                    </Button>
                    <Button type="primary" size="small" style="margin-right: 5px" @click="handleDebug(row.id)">调试
                    </Button>
                    <Button type="error" size="small" @click="handleRemove(row.id)">删除</Button>
                </template>
            </Table>
            <div style="margin-top: 20px">
                <Button @click="handleSelectAll(true)" style="margin-right: 5px">全选</Button>
                <Button @click="handleSelectAll(false)">取消全选</Button>
                <div style="float: right">
                    <Page :total="total" :current="page.page" :page-size="page.page_size" @on-change="handleChange"
                          @on-page-size-change="handleSize" show-sizer show-total show-elevator/>
                </div>
            </div>
        </div>
        <case-modal :title="caseTitle" :visible="visible" :caseId="caseId" :edit="edit"
                    @closeCaseModal="closeCaseModal"/>
        <case-result :show="show" :resultId="resultId" @closeResult="closeResult"/>
    </Card>
</template>

<script>
import interfaceModal from "@/components/interfaceModal";
import caseModal from "@/components/caseModal";
import caseResult from "@/components/caseResult";
import {apiAll, caseDebug, caseDownTemplate, caseExport, caseList, delApi, modules, userAll} from "@/utils/api";
import {formatDate} from "@/utils/common";
import CaseResult from "@/components/caseResult";
import fileDownload from "js-file-download";
import baseUrl from "@/utils/common";


const columns = [
    {
        type: 'selection',
        width: 60,
        align: 'center'
    },
    {
        title: '用例名称',
        key: 'name',
        render: (h, params) => {
            return h('div', [
                h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        overflow: 'hidden',
                        textOverflow: 'tooltip',
                        whiteSpace: 'nowrap'
                    },
                    domProps: {
                        title: params.row.name
                    }
                }, params.row.name)
            ])
        }
    },
    {
        title: '接口名称',
        key: 'interface_name',
        render: (h, params) => {
            return h('div', [
                h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        overflow: 'hidden',
                        textOverflow: 'tooltip',
                        whiteSpace: 'nowrap'
                    },
                    domProps: {
                        title: params.row.interface_name
                    }
                }, params.row.interface_name)
            ])
        }
    },
    {
        title: '请求URL',
        key: 'interface_path',
        render: (h, params) => {
            return h('div', [
                h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        overflow: 'hidden',
                        textOverflow: 'tooltip',
                        whiteSpace: 'nowrap'
                    },
                    domProps: {
                        title: params.row.domain + params.row.url
                    }
                }, params.row.domain + params.row.url)
            ])
        }
    },
    {
        title: '请求方式',
        key: 'method',
        width: 90,
    },
    {
        title: '创建人员',
        key: 'created_user',
        width: 120,
    },
    {
        title: '创建时间',
        key: 'created_time',
        render: (h, params) => {
            return h('div', [
                h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        overflow: 'hidden',
                        textOverflow: 'tooltip',
                        whiteSpace: 'nowrap'
                    },
                    domProps: {
                        title: formatDate(new Date(params.row.created_time), 'yyyy-MM-dd hh:mm:ss')
                    }
                }, formatDate(new Date(params.row.created_time), 'yyyy-MM-dd hh:mm:ss'))
            ])
        }
    },
    {
        title: '操作',
        slot: 'action',
        width: 220,
        align: 'center'
    }
]
export default {
    name: "case_list",
    data() {
        return {
            actionUrl: baseUrl + ":3000/api/v1/case_import",
            headers: {Authorization: "Bearer " + localStorage.getItem("token")},
            columns,
            data: [],
            selectData: [],
            moduleList: [],
            interfaceList: [],
            userList: [],
            visible: false,
            show: false,
            caseId: 0,
            edit: false,
            caseTitle: "",
            resultId: 0,
            total: 0,
            page: {
                page: 1,
                page_size: 10,
            },
            selectForm: {
                name: "",
                env_id: "",
                interface_id: "",
                created_by: "",
            }
        }
    },
    components: {
        CaseResult,
        interfaceModal,
        caseModal,
        caseResult
    },
    created() {
        // this.handleGetModules();
        // this.handleGetApi();
        // this.handleGetUsers();
        // this.query();
    },
    methods: {
        handleAdd() {
            this.caseTitle = "新建用例";
            this.visible = true;
        },
        closeCaseModal() {
            this.caseId = 0;
            this.visible = false;
            this.query();
        },
        handleEdit(id) {
            this.edit = true;
            this.caseTitle = "编辑用例";
            this.caseId = id;
            this.visible = true;
        },
        // closeModal() {
        //   this.show = false
        // },
        closeResult() {
            this.show = false
        },
        handleSelectAll(status) {
            this.$refs.selection.selectAll(status);
        },
        handleReset() {
            this.selectForm = {
                name: "",
                env_id: "",
                interface_id: "",
                created_by: "",
            }
            this.query();
        },
        handleSelect() {
            this.query()
        },
        handleGetModules() {
            const obj = {
                project_id: localStorage.getItem("project_id")
            }
            modules(obj).then(res => {
                this.moduleList = res.data.data;
            })
        },
        handleGetApi() {
            const obj = {
                project_id: parseInt(localStorage.getItem("project_id"))
            }
            apiAll(obj).then(res => {
                this.interfaceList = res.data.data;
            })
        },
        handleGetUsers() {
            userAll().then(res => {
                this.userList = res.data.data;
            })
        },
        handleChange(e) {
            this.page.page = e;
            this.query();
        },
        handleSize(e) {
            this.page.page_size = e
            this.query()
        },
        query() {
            const obj = {
                ...this.page,
                ...this.selectForm,
                project_id: parseInt(localStorage.getItem("project_id"))
            }
            caseList(obj).then(res => {
                this.data = res.data.data.rows
                this.total = res.data.data.count
            })
        },
        // 用例调试
        handleDebug(id) {
            caseDebug({"id": id}).then(res => {
                if (res.data.errno !== 0) {
                    this.$Message.error(res.data.errmsg)
                    return
                }
                this.$nextTick(() => {
                    this.show = true;
                    this.resultId = res.data.data
                })
            })

        },
        handleRemove(id) {
            console.log(id)
        },
        handleBatchExecution() {
            let data = this.selectData.map(item => {
                return item.id
            })
            console.log(data)
        },
        handleExport() {
            const obj = {
                ...this.page,
                ...this.selectForm,
                project_id: parseInt(localStorage.getItem("project_id"))
            }
            caseExport(obj).then(res => {
                fileDownload(res.data, '接口测试用例.xlsx');
            })
        },
        handleTemplate() {
            caseDownTemplate().then(res => {
                fileDownload(res.data, '用例模板.xlsx');
            })
        },
        handleClick(row) {
            this.selectData = row;
        },
        handleFormatError(file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。'
            })
        },
        handleSuccess(res, file) {
            if (res.data.errno === 0) {
                this.dialoLead = false
                this.$Message.success("数据导入成功！")
                this.query();
                this.$refs.upload.clearFiles()
            }
        },
        handleError(error, file) {
            this.$Message.error("数据导入失败！")
            this.$refs.upload.clearFiles()
        },
    }
}
</script>

<style>
.ivu-upload {
    width: auto !important;
}
</style>
